﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.Reflection;

public class LoadXML : MonoBehaviour {
	
	bool mIsReady = false;
	
	List<MethodParameter> methodList = new List<MethodParameter>();
	
	static LoadXML instance;
	
	public static LoadXML GetInstance()
	{
		return instance;
	}
	
	void Awake()
	{
		instance = this;
	}
	
	public void InitLoadXml(string filename, object classObj, MethodInfo method, LoaderManager.LoadTypeEnum type)
	{
		MethodParameter m = new MethodParameter();
		m.method = method;
		m.classObj = classObj;
		m.type = type;
		methodList.Add(m);
		string url = GameResources.LocalPath + filename;
		
		StartCoroutine(LoadXml(url, methodList.Count - 1));
	}
	
	IEnumerator LoadXml(string url, int index) 
	{ 
		WWW www = new WWW(url); 
		yield return www; 
		if (www.error == null) 
		{ 
			if(methodList[index].type == LoaderManager.LoadTypeEnum.XML)
			{
				methodList[index].method.Invoke(methodList[index].classObj, 
				new object[]{www.text, methodList[index].type});
			}
			else
			{
				string xml = www.text; 
				XmlDocument xmlDoc = new XmlDocument(); 
				xmlDoc.LoadXml(xml); 
				System.Xml.XmlNodeList Block = xmlDoc.GetElementsByTagName("ArrayOfUIResourceInfo");
				if(Block.Count>0)
				{
					XmlElement coun =  (XmlElement)Block.Item(0);
					ReadElement(coun, index);
				}
			}
			
		}
		www.Dispose(); 
		www = null;
	}
	
	void ReadElement(XmlElement blockele, int index)
	{
		if(blockele.ChildNodes.Count==0)
		{
			return;
		}
		XmlNode infonode = blockele.FirstChild;
		while(infonode!=null)
		{
			XmlElement pinfoele =(XmlElement)infonode;
			
			UIResourceInfo info = new UIResourceInfo();
			info.setOK = bool.Parse(pinfoele.GetAttribute("setOK"));
			info.level = int.Parse(pinfoele.GetAttribute("level"));
			info.sceneID = int.Parse(pinfoele.GetAttribute("sceneID"));
			info.Priority = int.Parse(pinfoele.GetAttribute("Priority"));
			info.localPath = GameResources.LocalPath + pinfoele.GetAttribute("localPath");
			
			methodList[index].list.Add(GetFileName(info.localPath).ToLower(), info);
			
			infonode=infonode.NextSibling;
		}
		mIsReady=true;
		
		if(index >= 0 && methodList.Count > index)
		{
			methodList[index].method.Invoke(methodList[index].classObj, 
				new object[]{methodList[index].list, methodList[index].type});
		}
	}
	
	public string GetFileName(string path)
	{	
		return System.IO.Path.GetFileNameWithoutExtension(path);
	}
	
	public bool IsReady
	{
		get{return mIsReady;}
	}
	
}

public class MethodParameter
{
	public MethodInfo method;
	public object classObj;
	public LoaderManager.LoadTypeEnum type;
	public Dictionary<string, UIResourceInfo> list = new Dictionary<string, UIResourceInfo>();
}
